package ee.az.test.wave;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;

import javax.swing.JPanel;

/**
 * @author Artur Zinatullin (artur.zinatullin@gmail.com) 2011
 */
public class FieldCanvas extends JPanel {
	private static final long serialVersionUID = 1L;

	private final Field field;
	private Image offImage;

	public FieldCanvas(Field field) {
		super();
		this.field = field;
		setSize(field.getWidth(), field.getHeight());
		setPreferredSize(new Dimension(field.getWidth(), field.getHeight()));
	}

	@Override
	public void paintComponent(Graphics g) {
		int height = field.getHeight();
		int width = field.getWidth();

		if (offImage == null) {
			offImage = createImage(width, height);
		}

		if (!field.isValid()){
			Graphics graphics = offImage.getGraphics();
			for (int x = 0; x < width; x++) {
				for (int y = 0; y < width; y++) {
					Cell cell = field.getCell(x, y);
					graphics.setColor(getColor(cell));
					graphics.drawLine(x, y, x+1, y+1);
				}
			}
			field.validate();
		}

		g.drawImage(offImage, 0, 0, this);
	}

	private Color getColor(Cell cell) {
		//FIXME out of range
		return new Color((float)(0.5 + cell.getHeight()), (float)(0.5 + cell.getHeight()), (float)(0.5 + cell.getHeight()));
	}
}
